import {
  fetchHome
} from '../../services/home/home';
import {
  fetchGoodsList
} from '../../services/good/fetchGoods';
import {
  ds
} from '../../tools/data'
import {
  dsx
} from '../../tools/datax'
import {
  localData
} from '../../tools/localData'
import {
  users
} from '../../tools/users';
import {
  cartTool
} from '../../tools/cartTool';
import {
  ui
} from '../../tools/ui';
import {
  nav2
} from '../../tools/nav2';
import {
  adv
} from '../../tools/adv';
import {
  clipboardTool
} from './clipboard';
import {
  resource
} from '~/static/resource';

Page({
  data: {
    user: null,
    imgSrcs: [],
    tabList: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: 500,
    interval: 5000,
    navigation: {
      type: 'dots'
    },
    swipers: [],
    modules: [],
    action: 'home',
    tabIndex: 0,
    scrollTexts: [],
    curText: ''
  },
  goodListPagination: {
    index: 0,
    num: 20,
  },
  // privateData: {
  //   tabIndex: 0,
  // },
  onShow() {
    this.parseClipBoard()
    this.getTabBar().init()
  },
  onReady() {
    this.ready = true
    this.parseClipBoard()
  },
  onLoad(options) {
    // console.log(options)
    wx.showShareMenu({
      withShareTicket: true
    })
    this.setData({
      shareUserOpenid: options.shareUserOpenid
    })
    this.init()
    this.bindStaff()
    this.loadBg()
  },
  loadBg() {
    ui.getCloudFileUrl(resource.img.homeBg, url => {
      this.setData({
        homeBg: url
      })
    })
  },
  scrollText(swipers) {
    const scrollTexts = swipers.filter(ele => ele.text)
    if (!scrollTexts || scrollTexts.length <= 0) return

    if (typeof this.scrollTextIndex == 'undefined') this.scrollTextIndex = 0
    const that = this
    const updater = () => {
      that.setData({
        curText: scrollTexts[this.scrollTextIndex]
      })
      that.scrollTextIndex = (that.scrollTextIndex + 1) % scrollTexts.length
    }
    updater()
    this.scrollTextTimer = setInterval(updater, 3000);
  },
  async bindStaff() {
    const {
      shareUserOpenid
    } = this.data
    if (!shareUserOpenid) return

    const user = await this.loadUser()
    const res = await adv.bind(user._openid, shareUserOpenid)
    // console.log(res)
  },
  onReachBottom() {
    if (this.data.noMore) return

    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },
  onPullDownRefresh() {
    this.init();
  },
  init() {
    this.loadHomePage();
  },
  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
      noMore: false
    });

    // this.loadSwipers()
    this.loadModules()
    this.loadTags()
    this.doFetchHome() // goods
  },
  async parseClipBoard() {
    if (!this.ready) return

    const user = await this.loadUser()
    if (user.role != 'admin' && user.role != 'master' && user.role != 'delivery') return

    const clip = this.getTabBar().getClipboardComponent()
    return clip && clip.activate()

    wx.getClipboardData({
      async success(res) {
        wx.hideToast()
        const data = res.data // clipboard data

        if (clipboardTool.isProcessed(data)) return
        clipboardTool.setProcessed(data)

        const actionSheet = {}
        let mobile, msgNum, orderId
        if (mobile = clipboardTool.getMobile(data)) actionSheet.mobile = '用户' + mobile
        if (msgNum = clipboardTool.getMsgNum(data)) actionSheet.msg = '消息列表'
        if (orderId = clipboardTool.getOrderId(data)) actionSheet.order = '订单' + orderId

        if (Object.keys(actionSheet).length == 0) return
        ui.actionSheet(actionSheet, (desc, key) => {
          clipboardTool.act(key, mobile, msgNum, orderId)
        })
      },
      fail(err) {
        console.error(err)
      }
    })
  },
  loadModules() {
    const _ = ds.cmd,
      that = this
    ds.coll('module')
      .where({
        _id: _.exists(true)
      })
      .limit(10)
      .orderBy('pos', 'asc')
      .get()
      .then(function (res) {
        const modules = res.data
        that.setData({
          modules
        })
        that.initPopup(modules)
        modules.forEach((element, index) => {
          if (element.type == "msg") ui.getCloudFileUrl(element.img, url => {
            modules[index].bgImg = url
            that.setData({
              modules
            })
          })
        });
      });
  },
  initPopup(modules) {
    const popup = modules.find(ele => ele.type == 'popup')
    if (!popup) return
    const showPopup = this.judgeShowPopup(popup)
    // console.log(showPopup)
    this.setData({
      showPopup,
      popup
    })
  },
  judgeShowPopup(popup) {
    if (!popup.visible || !popup.slides || popup.slides.length == 0) return false
    const popupLastShowTime = localData.get('popupLastShowTime')
    if (!popupLastShowTime || !popup.dayNum) return true

    const diff = (Date.now() - popupLastShowTime) / (1000 * 60 * 60 * 24) // days
    return diff >= popup.dayNum
  },
  closePopupTap() {
    localData.set('popupLastShowTime', Date.now())
    this.setData({
      showPopup: false
    })
  },
  // 加载标签
  loadTags() {
    const tags = [{
      text: '所有商品',
      key: 0
    }]
    const _ = ds.cmd,
      that = this
    dsx.getAll('goods', {
      tags: _.exists(true),
      visible: _.or(_.eq("true"), _.eq(true)),
    }, {
      tags: true
    }).then(data => {
      const tagMap = {}
      for (let goods of data) {
        goods.tags.map(x => {
          const trimmed = x.trim()
          if (!tagMap[trimmed]) tags.push({
            text: x.trim(),
            key: tags.length
          })
          tagMap[trimmed] = true
        })
      }
      that.setData({
        tabList: tags
      })
    })
  },
  doFetchHome() {
    fetchHome().then(() => {
      this.setData({
        pageLoading: false,
        noMore: false
      });
      this.loadGoodsList(true); // load goods
    });
  },
  // 点击标签
  tabChangeHandle(e) {
    const tabIndex = e.detail.value
    // this.privateData?.tabIndex = tabIndex;
    this.switchTab(tabIndex)
    ui.scrollTo('home-page-tags')
  },
  switchTab(tabIndex) {
    this.setData({
      tabIndex
    })
    this.loadGoodsList(true, this.getTag())
  },
  getTag() {
    const {
      tabIndex
    } = this.data
    if (tabIndex <= 0) return ''
    return this.data.tabList[tabIndex]?.text || ''
  },
  onReTry() {
    this.loadGoodsList();
  },
  // 加载货物，tag指示首页或水票
  async loadGoodsList(fresh = false, tag = '') {
    const that = this
    const action = ((tag || this.action) == 'ticket' ? 'ticket' : 'home')
    this.setData({
      action
    })
    this.action = action
    wx.setNavigationBarTitle({
      title: action == 'home' ? '营业时间 08:30-19:30' : '水票'
    })
    // console.log(action, tabIndex)
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
        noMore: false
      });
    }

    this.setData({
      goodsListLoadStatus: 1
    });

    const pageSize = this.goodListPagination?.num || 4;
    let pageIndex = (this.pageIndex >= 0 ? this.pageIndex + 1 : 0)
    // this.privateData?.tabIndex * pageSize + this.goodListPagination?.index + 1 || 0;
    if (fresh) {
      pageIndex = 0;
    }
    this.pageIndex = pageIndex

    try {
      await fetchGoodsList(pageIndex, pageSize, action == 'ticket' ? '_ticket_' : this.getTag(), nextList => {
        that.goodsListFetched(fresh, nextList, pageIndex, pageSize)
      });
      this.getTabBar().setData({
        active: action == 'home' ? 0 : 2
      })
    } catch (err) {
      this.setData({
        goodsListLoadStatus: 3
      });
    }
  },
  goodsListFetched(fresh, nextList, pageIndex, pageSize) {
    this.setData({
      goodsList: fresh ? nextList : this.data.goodsList.concat(nextList),
      goodsListLoadStatus: 0,
      noMore: nextList.length < pageSize
    });

    (this.goodListPagination || {}).index = pageIndex;
    (this.goodListPagination || {}).num = pageSize;
  },
  goodListClickHandle(e) {
    const {
      index
    } = e.detail;
    const {
      spuId,
      _id
    } = this.data.goodsList[index];
    // console.log(this.data.action)
    const showTicket = (this.data.action == 'ticket')
    const showTicketParam = (showTicket ? '&showTicket=true' : '')
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${_id}${showTicketParam}`,
    });
  },
  async goodListAddCartHandle(e) {
    let user = await this.loadUser()
    cartTool.add({
      ...e.detail.goods,
      vip: user.vip || false
    }, false)
    this.makeAdd2CartAnimate(e.detail, () => {
      this.getTabBar().countCartGoodsNum()
    })
  },
  async makeAdd2CartAnimate(detail, cb) {
    const {
      index,
      goods
    } = detail

    const goodsListComponent = this.selectComponent('#goodsListComponent')
    const goodsPos = await goodsListComponent.getGoodsCardPosition(index)
    this.setData({
      goodsImage: goods.images[0],
      isAnimating: true,
      startX: goodsPos.left,
      startY: goodsPos.top,
    })

    const cartPos = await this.getTabBar().getCartTabPosition()
    const winWidth = wx.getWindowInfo().windowWidth,
      winHeight = wx.getWindowInfo().windowHeight
    const animation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease'
    })
    const diffX = cartPos.left - (goodsPos.left + 46 * (winWidth / 100) / 2 - 20);
    const diffY = cartPos.top - (goodsPos.top + 60)
    animation.translate(diffX, diffY).scale(0).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(() => {
      this.setData({
        isAnimating: false,
        animationData: {},
        goodsImage: ''
      })
      if (cb) cb()
    }, 800)
  },
  async loadUser() {
    if (this.data.user) return this.data.user

    const user = await users.getUserInfo()
    this.setData({
      user
    })
    return user
  },
  navToSearchPage() {
    wx.navigateTo({
      url: '/pages/goods/search/index'
    });
  },
  navToActivityDetail(e) {
    const item = ui.eventData(e, 'item')
    // console.log(item)
    if (item.linkSel) nav2.goodsDetail(item.link, item.showTicket)
    else if (item.showPromotion) nav2.promotion()
    else if (item.speedArrival) nav2.fastDelivery()
    else if (item.buyTicket) this.getTabBar().navigateToTab(2)
    else if (item.goodsGroupSel) {
      const tabList = this.data.tabList
      const tab = tabList.findIndex(ele => {
        // console.log(ele, item.goodsGroup)
        return ele?.text.indexOf(item.goodsGroup) >= 0
      })
      if (tab >= 0) {
        this.switchTab(tab);
        ui.scrollTo('home-page-tags')
      }
    }
  },
  onShareAppMessage() {
    console.log(`/pages/home/home?shareUserOpenid=${this.data.user._openid}`)
    const customInfo = {
      // imageUrl: this.data.details.primaryImage,
      title: '万家顺送水-微信小程序',
      path: `/pages/home/home?shareUserOpenid=${this.data.user._openid}`,
    };
    return customInfo;
  },
});